package org.gw.building.ctrl;

import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.context.Roles;
import org.gw.ylc.base.model.UserInfo;
import org.gw.ylc.base.service.AuthenticateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
@RequestMapping("login")
public class LoginCtrl {
	@Autowired
	private AuthenticateService authenicateService;
	@Value("#{config['auth.mode']}")
	private String authMode = "db";

	@RequestMapping("login")
	@ResponseBody
	public Object login(HttpServletRequest request, String username, String password) {
		List<UserInfo> users = authenicateService.authenticate(request, "train");
		if (!CollectionUtils.isEmpty(users)) {
			HttpSession session = request.getSession(true);
			for (UserInfo user : users) {
				user.setPassword(null);
			}
			session.setAttribute("_users_", users);
			session.setAttribute("_current_user_", users.get(0));
			return users.get(0).getType();// 默认取第一个用户的角色，后面可以进行角色切换
		}
		return "";
	}

	@RequestMapping("switchRole")
	public void switchRole(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			Integer toRole) throws IOException {
		UserInfo currentUser = (UserInfo) session.getAttribute("_current_user_");
		if (currentUser.getType() == toRole.intValue()) {// 无需切换
			response.sendRedirect(getIndexURL(request));
			return;
		}
		List<UserInfo> users = (List<UserInfo>) session.getAttribute("_users_");
		for (UserInfo user : users) {
			if (user.getType() == toRole.intValue()) {
				session.setAttribute("_current_user_", user);
				response.sendRedirect(getIndexURL(request));
				return;
			}
		}
	}

	@RequestMapping("getCurrent")
	@ResponseBody
	public Object getCurrent(HttpSession session) {
		Set<Roles> roles = RequestContextHolder.get().getAvailableRoles();
		List<OrderMap<String, Object>> l = new ArrayList<OrderMap<String, Object>>();
		for (Roles r : roles) {
			OrderMap<String, Object> rMap = new OrderMap<String, Object>();
			rMap.put("type", r.ordinal());
			rMap.put("label", r.getLabel());
			l.add(rMap);
		}
		Collections.sort(l);
		return new Object[] { RequestContextHolder.get().getUser(), l, RequestContextHolder.get().getUser().getType() };
	}

	class OrderMap<K, V> extends HashMap implements Comparable<Map> {
		@Override
		public int compareTo(Map o) {
			return (Integer) this.get("type") - (Integer) o.get("type");
		}
	}

	@RequestMapping("getLoginUrl")
	@ResponseBody
	public Object getLoginUrl(HttpServletRequest request) throws UnsupportedEncodingException {
		if ("ids".equalsIgnoreCase(authMode)) {
			return authenicateService.getICELoginUrl(getIndexURL(request), "");
		} else {
			return "";
		}
	}

	@RequestMapping("logout")
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession(true);
		session.invalidate();
		if ("ids".equalsIgnoreCase(authMode)) {
			String logoutUrl = authenicateService.getICELogoutUrl(getIndexURL(request));
			response.sendRedirect(logoutUrl);
		} else {
			response.sendRedirect(getIndexURL(request));
		}
	}

	private String getIndexURL(HttpServletRequest request) {
		String path = request.getContextPath();
		String indexURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/index.html";
		return indexURL;
	}
}
